package edu.ccit.shudong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.ccit.shudong.dto.UserPasswordResetDTO;
import edu.ccit.shudong.dto.UserProfileDTO;
import edu.ccit.shudong.dto.UserRegisterDTO;
import edu.ccit.shudong.entity.User;
import edu.ccit.shudong.mapper.UserMapper;
import edu.ccit.shudong.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ccit.shudong.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Suting Luo
 * @since 2024-06-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Value("${token.secret}")
    private String secret;

    @Value("${bed.url.prefix}")
    private String bedUrlPrefix;

    @Override
    public boolean register(UserRegisterDTO userRegisterDTO) {
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPassword(new BCryptPasswordEncoder().encode(userRegisterDTO.getPassword()));
        return this.save(user);
    }

    @Override
    public String login(String username, String password) {
        // 根据用户名读取用户信息
        User user = this.getOne(new QueryWrapper<User>().eq("username", username));
        // 用加密算法去验证密码是否正确
        if (user != null && new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            return JwtUtils.sign(user.getId(), user.getUsername(), secret);
        }
        else {
            return null;
        }
    }

    @Override
    public UserProfileDTO getProfileByToken(String token) {
        long userId = JwtUtils.getUserId(token);
        User user = this.getById(userId);
        user.setAvatar(bedUrlPrefix + user.getAvatar());
        UserProfileDTO userDTO = new UserProfileDTO();
        userDTO.fromUser(user);
        return userDTO;
    }

    @Override
    public boolean resetPassword(String token, UserPasswordResetDTO passwordResetDTO) {
        long userId = JwtUtils.getUserId(token);
        User user = this.getById(userId);
        if (user != null && new BCryptPasswordEncoder().matches(passwordResetDTO.getOldPassword(), user.getPassword())) {
            user.setPassword(new BCryptPasswordEncoder().encode(passwordResetDTO.getNewPassword()));
            return this.updateById(user);
        }
        return false;
    }


}
